//导入工具包 require('node_modules里对应模块')
var gulp = require('gulp'), //本地安装gulp所用到的地方
    less = require('gulp-less');
var miniCss = require('gulp-clean-css');
var babel = require('gulp-babel');
var miniJs = require('gulp-uglify');
var concat = require('gulp-concat');
var fs = require('fs');
var gulpif = require('gulp-if');
var miniHtml = require('gulp-htmlmin');
var rename = require('gulp-rename');
var watch = require('gulp-watch');
// var browserSync = require('browser-sync');
// var jshint = require('gulp-jshint');
var config = require('/files/gulp-project.conf');

/******** 车位配置 start   ******************/
var carConfig={
    fileMap:{}
    ,modules:[]
    ,baseTech:'/files/'
    // js技术框架
    ,techJsArr:config.car.techJsArr
    // css技术框架
    ,techCssArr:config.car.techCssArr
    ,baseDir:'/files/car/'
};
/**
    gulp.conf 配置 {transFiles:[
        {src:['src1.js','src2.js',...],dest:'dest1.js'},
        {src:['src1.js','src3.js',...],dest:'dest2.js'},
        ...
    ]}
    转换fileMap: {
        src:[
            {src:['src1.js','src2.js',...],dest:'dest1.js'},
            {src:['src1.js','src3.js',...],dest:'dest2.js'},
            ...
        ]
    }

    css 、js 指定路径 project/dist/
    html 指定路径 project/
**/
gulp.task("carConf", function () {
    // 浏览器自动刷新
    // browserSync.init({
    //     server: {
    //         // baseDir: carConfig.baseDir,
    //          proxy: "http://localhost:8086/car/sa"
    //     }
    // });
    // 需要处理的文件映射
    var srcDir = carConfig.baseDir;
    var dir = fs.readdirSync(srcDir).filter(function (file) {
         return fs.statSync(srcDir + file).isDirectory();
     });
     dir.map(function (dir) {
        fs.exists(srcDir+dir+'/gulp-project.conf',function(exists){
            if(exists){
                 var c = require(srcDir+dir+'/gulp-project.conf');
                 if(c && c.transFiles){
                    carConfig.modules.push(dir);
                    //只需要执行一次watch即可
                    autoCar(dir);
                    c.transFiles.forEach(function(o){
                        o.src.forEach(function(src,i){
                            src = carConfig.baseDir + dir + '/' + src;
                            o.src[i] = src; // 修改源码路径加上模块名
                            o.module = dir;
                            if(carConfig.fileMap[src]){
                                carConfig.fileMap[src].push(o);
                            }
                            else{
                                carConfig.fileMap[src] = [o];
                            }
                        });
                    });
                 }
            }
        });
     });
});


// js 压缩 es6 转换 
function carJs(obj) {
    var arr = obj.dest.split('/');
    gulp.src(obj.src)
        .pipe(concat(arr.pop())) //该任务调用的模块  把源码拼接在一起
        // .pipe(babel({  // 语法转成es5
        //     presets: ['env']  
        // }))
        .pipe(miniJs({mangle:{ // 压缩js代码
            // toplevel :true //默认值false。
        }}))
        .pipe(gulp.dest(carConfig.baseDir+obj.module+'/dist/'+arr.join('/')));  // 保存到目的文件
}
// css 压缩 less 转换 
function carCss(obj) {
    var arr = obj.dest.split('/');
    gulp.src(obj.src)
        .pipe(concat(arr.pop())) //该任务调用的模块
        .pipe(less())
        .pipe(miniCss())
        .pipe(gulp.dest(carConfig.baseDir+obj.module+'/dist/'+arr.join('/'))); 
}
// html 压缩  
function carHtml(obj) {
    var options = {
        removeComments: true,//清除HTML注释
        collapseWhitespace: true,//压缩HTML
        collapseBooleanAttributes: true,//省略布尔属性的值 <input checked="true"/> ==> <input />
        removeEmptyAttributes: true,//删除所有空格作属性值 <input id="" /> ==> <input />
        removeScriptTypeAttributes: true,//删除<script>的type="text/javascript"
        removeStyleLinkTypeAttributes: true,//删除<style>和<link>的type="text/css"
        minifyJS: true,//压缩页面JS
        minifyCSS: true//压缩页面CSS
    };
    var arr = obj.dest.split('/');
    // console.log(arr.pop());
    // console.log(carConfig.baseDir+obj.module+'/'+arr.join('/'));
    gulp.src(obj.src)
        .pipe(miniHtml(options))
        .pipe(rename(arr.pop()))
        .pipe(gulp.dest(carConfig.baseDir+obj.module+'/'+arr.join('/')));
}

function autoCar(module){
    console.log('auto')
    // 监测项目下所有js改动
    watch([carConfig.baseDir+module+'/**/*.js','!'+carConfig.baseDir+module+'/dist/**/*.js'], function(event) {
        var path = event.path.replace(/\\/g,'/');
        var carIn = path.indexOf('/car/');
        var src = carConfig.baseDir + path.substring(carIn+5);
        console.log("[\x1B[90m"+new Date().toLocaleTimeString()+'\x1B[39m] File ' + event.path + ' was ' + event.event );
        if(!carConfig.fileMap[src]){
            console.warn("[\x1B[90m"+new Date().toLocaleTimeString()+'\x1B[39m] File ' + event.path + ' was ' + event.event + ',but no task match...' );
            return ;
        }
        // 对每个目的文件进行压缩
        carConfig.fileMap[src].forEach(function(o){
            carJs(o,module);
        });
        changeCarResVer(1,module);
        // browserSync.reload();
    });
    // 监测项目下所有css改动
    watch([carConfig.baseDir+module+'/**/{*.css,*.less}','!'+carConfig.baseDir+module+'/dist/**/*.css'], function(event) {
        var path = event.path.replace(/\\/g,'/');
        var carIn = path.indexOf('/car/');
        var src = carConfig.baseDir + path.substring(carIn+5);
        console.log("[\x1B[90m"+new Date().toLocaleTimeString()+'\x1B[39m] File ' + event.path + ' was ' + event.event );
        if(!carConfig.fileMap[src]){
            console.error("[\x1B[90m"+new Date().toLocaleTimeString()+'\x1B[39m] File ' + event.path + ' was ' + event.event + ',but no task match...' );
             return ;
        }
        carConfig.fileMap[src].forEach(function(o){
            carCss(o);
        });
        changeCarResVer(1,module);
        // browserSync.reload();
    });   
    // 监测项目下 html 改动
    watch(carConfig.baseDir+module+'/{index.s.html,mp.s.html}', function(event) {
        var path = event.path.replace(/\\/g,'/');
        var carIn = path.indexOf('/car/');
        var src = carConfig.baseDir + path.substring(carIn+5);
        console.log("[\x1B[90m"+new Date().toLocaleTimeString()+'\x1B[39m] File ' + event.path + ' was ' + event.event );
        if(!carConfig.fileMap[src]){
            console.error("[\x1B[90m"+new Date().toLocaleTimeString()+'\x1B[39m] File ' + event.path + ' was ' + event.event + ',but no task match...' );
             return ;
        }
        carConfig.fileMap[src].forEach(function(o){
            carHtml(o);
        });
        // changeCarResVer(1,module);
        // browserSync.reload();
    });
}
// 执行合并js技术框架
gulp.task('techCarJs',function(){
    var srcArr = [];
    carConfig.techJsArr.forEach(function(o){
        srcArr.push(carConfig.baseTech+o);
    });
    gulp.src(srcArr)
    // es 6 转换 template.js 会报错
        // .pipe(babel({  
        //     presets: ['es2015']  
        // }))
        .pipe(concat('tech.min.js'))
        .pipe(miniJs({mangle:{
              toplevel    : true //默认值false。
          }}))
        .pipe(gulp.dest(carConfig.baseDir));
    changeCarTechVer(1);
}); 

// 执行合并css技术框架
gulp.task('techCarCss',function(){
    var srcArr = [];
    carConfig.techCssArr.forEach(function(o){
        srcArr.push(carConfig.baseTech+o);
    });
    gulp.src(srcArr)
    .pipe(concat('tech.min.css')) //该任务调用的模块
    .pipe(less())
    .pipe(miniCss())
    .pipe(gulp.dest(carConfig.baseDir)); 
    changeCarTechVer(1);
}); 
/* 修改项目资源版本**/
function changeCarResVer(resVer="",module=""){
    console.log(resVer);
    console.log(module);
    if(resVer && module){
        var v = (Math.random()+"").substring(2);
        fs.writeFile(carConfig.baseDir+module+'/res.ver',v,function(error){
            if(error){
                console.error(error);
            }
        });
    }
}
/* 修改技术资源版本**/
function changeCarTechVer(techVer=""){
    if(techVer){
        var v = (Math.random()+"").substring(2);
        config.car.techVer = v;
        var conStr = JSON.stringify(config)
                .replace(/\",\"/g,'\",\n\t\"')
                .replace(/\},\"/g,'\},\n\t\"')
                .replace(/\],\"/g,'\],\n\t\"')
                .replace(/\{\"/g,'\{\n\t\"')
                .replace(/:\[\"/g,':\[\n\t\"');
        fs.writeFile(carConfig.baseTech+'gulp-project.conf',"module.exports="+conStr,function(error){
            if(error){
                console.error(error);
            }
        });
    }
}
// gulp.task('jshint', function () {
//   return gulp.src([
//     './car/sample/Scripts/define.js'
//   ]).pipe(jshint())
//     .pipe(jshint('jshintrc.json'))
//     .pipe(jshint.reporter('jshint-stylish'))
//     .pipe(jshint.reporter('fail'));
// });

/******** 车位配置 end   ******************/

gulp.task('default',function(){
    console.log('default');
    changeCarTechVer(1);
}); //定义默认任务

